#!/bin/bash
SERVERS=(192.168.47.201 192.168.47.202 192.168.47.203 192.168.47.204 192.168.47.205)
PASSWORD=root
cat /root/.ssh/id_rsa.pub
if [ $? -eq 0 ]
then 
	echo "ssh 公钥已经存在,不用创建了"
else
	echo "ssh 公钥不存在，立即生成"
	expect -c "set timeout -1;
        spawn ssh-keygen;
        expect {
            *id_rsa* {send -- \r;exp_continue;}
            *passphrase* {send -- \r;exp_continue;}
			*again* {send -- \r;exp_continue;}
            eof        {exit 0;}
        }";
fi

# 开始复制公钥
# expect 模拟人机交互
# \r 表示回车
# set timeout -1 一直等待输入提示
# spawn 执行命令
# expect {} 里面的对话 
# eof 结束 expect
auto_ssh_copy_id() {
	expect -c "
		set timeout -1;
		spawn ssh-copy-id $1;
		expect {
			*(yes/no)* {send -- yes\r;exp_continue;}
			*password:* {send -- $2\r;exp_continue;}
			eof {exit 0;}
		}
	";
}

echo "开始 ssh-copy-id "
for ((i=0;i<${#SERVERS[@]};i++))
do
	echo "复制到 ${SERVERS[i]}"
	auto_ssh_copy_id ${SERVERS[i]} $PASSWORD
done



